<script lang="ts" setup>
import OSS from "ali-oss";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncgetteamflow, asyncupdateteamflow, ossupload } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TaskType } from "@/util/type";

const router = useRouter();
const store = useStore(Storekey);
// 当前登录用户
const user = computed(() => {
  return store.state.user;
});
const teamid = computed(() => {
  return user.value?.teamid;
});

const props = defineProps<{
  selectedTask: Studycodemodel.Iteamjob;
  taskTypeInfoCfg: Record<
    TaskType,
    { title: string; conditionText: (num: number, degree?: number) => string }
  >;
  teamFiles: Studycodemodel.Iteamfile[];
}>();

const taskType = computed(() => {
  return props.selectedTask.type || TaskType.QUESTION;
});

const tableData = computed(() => {
  const data = props.selectedTask.teamjobrelation
    ?.filter((e) => e.userid === user?.value?.ID)
    .map((n) => {
      const e = props.teamFiles.find((z) => z.ID === n.teamfileid);
      const index =
        props.selectedTask.jobquestion?.find(
          (z) => n.teamfileid === z.teamfileid
        )?.index || 0;
      return {
        ...e,
        state: n.state,
        teamfileid: n.teamfileid,
        index,
        teamjobid: props.selectedTask.ID,
      };
    })
    .sort((a, b) => a.index - b.index);
  // return data || []
  //
  return props.teamFiles
    .map((target) => {
      let myTaskRelation = props.selectedTask.teamjobrelation?.find(
        (e) => e.userid === user.value?.ID && e.teamfileid === target.ID
      );
      const jobquestion = props.selectedTask.jobquestion?.find(
        (z) => target.ID === z.teamfileid
      );
      return {
        ...target,
        state: myTaskRelation ? myTaskRelation.state : false,
        myTaskRelation: !!myTaskRelation,
        teamfileid: jobquestion?.teamfileid,
        index: jobquestion?.index || 0,
        teamjobid: props.selectedTask.ID,
      };
    })
    .sort((a, b) => a.index - b.index);
});

onMounted(() => {
  // 初始化oss
  start();
});

const oss = ref<OSS>();
async function start() {
  const res = await ossupload();
  oss.value = new OSS({
    region: "oss-cn-qingdao",
    accessKeyId: res.accessKeyId,
    accessKeySecret: res.accessKeySecret,
    stsToken: res.securityToken,
    bucket: "ojteam",
    refreshSTSToken: async () => {
      const info = await ossupload();
      return {
        accessKeyId: info.accessKeyId,
        accessKeySecret: info.accessKeySecret,
        stsToken: info.securityToken,
      };
    },
  });
  setflow();
}
const flow = ref<Studycodemodel.Iteamflow>();
async function setflow() {
  try {
    flow.value = await asyncgetteamflow({ teamid: teamid.value });
  } catch (e) {
    flow.value = undefined;
    console.log(e);
  }
}
function renderSize(value: number) {
  if (!value) {
    return "0 Bytes";
  }
  var unitArr = new Array(
    "Bytes",
    "KB",
    "MB",
    "GB",
    "TB",
    "PB",
    "EB",
    "ZB",
    "YB"
  );
  var index = 0;
  var srcsize = parseFloat(String(value));
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  var size = srcsize / Math.pow(1024, index);
  return size.toFixed(2) + unitArr[index];
}
const useflow = computed(() => {
  const {
    usesize = 0,
    size = 1021 * 1024 * 1024 * 5,
    flow: _flow = 1021 * 1024 * 1024 * 10,
    useflow = 0,
  } = flow.value || {};
  return {
    size: renderSize(size),
    usesize: renderSize(usesize),
    flow: renderSize(_flow),
    useflow: renderSize(useflow),
    percentageflow: Math.floor((useflow / _flow) * 100),
    percentagesize: Math.floor((usesize / size) * 100),
    _usesize: usesize,
    _size: size,
    _flow: _flow,
    _useflow: useflow,
  };
});
async function fileClick(row: any) {
  if (useflow.value._useflow > useflow.value._flow) {
    ElMessage.error("本月团队资料流量已用完，如需帮助请联系助教老师或管理员");
    return;
  }
  const data = oss.value?.signatureUrl(String(row.url), {
    expires: 300,
  });
  await asyncupdateteamflow({
    ID: flow.value?.ID,
    useflow: flow.value?.useflow,
    size: row.size,
    teamid: teamid.value,
    name: row.name,
    teamfileid: row.ID,
  });
  window.open(data, "_blank");
  if (setflow) {
    setflow();
  }
}
</script>

<template>
  <div class="taskItem-container-box">
    <div class="">
      <!-- <el-descriptions :title="selectedTask.name" :column="2" size="large">
                <el-descriptions-item :span="2" label="任务完成条件:">
                    {{ taskTypeInfoCfg[taskType].conditionText(selectedTask.questionnum || 0,
                selectedTask.questionac) }}
                </el-descriptions-item>
            </el-descriptions> -->
    </div>
    <div class="">
      <el-table :data="tableData" @row-click="fileClick" style="width: 100%">
        <template v-slot:empty>
          <el-empty
            image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png"
          />
        </template>
        <el-table-column
          label="序号"
          type="index"
          width="100"
        ></el-table-column>
        <el-table-column prop="ID" label="文件ID" width=""></el-table-column>
        <el-table-column
          prop="name"
          label="文件名称"
          width=""
        ></el-table-column>
        <el-table-column prop="size" label="文件大小" width="">
          <template #default="{ row }">
            {{ renderSize(Number(row.size)) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="我的进度">
          <template #default="{ row }">
            <el-icon>
              <el-icon>
                <circleCheckFilled
                  color="#67C23A"
                  v-show="row.myTaskRelation && row.state"
                />
                <WarningFilled
                  color="#F56C6C"
                  v-show="row.myTaskRelation && !row.state"
                />
                <WarnTriangleFilled
                  color="#F56C6C"
                  v-show="!row.myTaskRelation"
                />
              </el-icon>
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style scoped></style>
